package com.skj.server;

import java.io.* ;
import javax.servlet.http.* ;
import com.google.appengine.api.datastore.* ;
import com.google.appengine.api.users.* ;

@SuppressWarnings("serial")
public class UserServlet extends HttpServlet
{
	private UserDatabase userDatabase ;
	
	public UserServlet()
	{
		userDatabase = new UserDatabase() ;
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException
	{
		
	}
	
	// Retrieves and Creating a user's page
	public void doGet(HttpServletRequest req, HttpServletResponse resp)throws IOException
	{
		com.google.appengine.api.users.User user ;
		UserService userService = UserServiceFactory.getUserService() ;
		
        String thisURL = req.getRequestURI();
        
        if (req.getUserPrincipal() != null)
        {
        	user = userService.getCurrentUser() ;
        	
        	UserRecord userRecord = userDatabase.retrieveUserRecord(user) ;
        	
        	if(userRecord == null)
        	{
        		// CREATING A NEW USER
        		userDatabase.createUserRecord(user) ;
        		
        		resp.getWriter().println("<p>Hello, " +
                        req.getUserPrincipal().getName() +
                        "!  You have been successfully added as a user</p>");
        	}
        	else
        	{
        		// WELCOMING an EXISTING USER
        		resp.getWriter().println("<p>Thanks for coming again, " +
                                         req.getUserPrincipal().getName() +
                                         "!  You can <a href=\"" +
                                         userService.createLogoutURL(thisURL) +
                                         "\">sign out</a>.</p>");
        	}
        }
        else // if no user signed in
        {
            resp.getWriter().println("<p>Please <a href=\"" +
                                         userService.createLoginURL(thisURL) +
                                         "\">sign in</a>.</p>");
        }
		
		// Will be filled afterwards with the following:
		// Widget Container
		// Widget - User Name 
		// Widget - User's Document List
		// Widget - User's Active Document Widgets (Execution Tool, WYSIWYG Editor, Network Tool)
		// Widget - User Account
	}
	
	// Updates a user's data
	public void doPut(HttpServletRequest req, HttpServletResponse resp)throws IOException
	{
		
	}
	
	// Deletes a user
	public void doDelete(HttpServletRequest req, HttpServletResponse resp)throws IOException
	{
		
	}
}
